<template>
  <el-dialog
    :before-close="beforeClose"
    :visible.sync="show"
    :title="title"
    width="30%"
    @close="close"
    @closed="closed"
  >
    <el-checkbox-group v-model="checkedBuilding" @change="handleChange">
      <el-checkbox v-for="building in buildingList" :key="building.id" :label="building.id">{{ building.name }}</el-checkbox>
    </el-checkbox-group>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import select from '@/list/select'
import { getUserBuildings, setUserBuildings } from '@/api/system'
export default {
  name: 'Range',
  mixins: [select],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      show: false,
      checkedBuilding: []
    }
  },
  computed: {
    title() {
      return '范围编辑'
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.show = val
        this.getData()
      }
    }
  },
  mounted() {
    this.show = this.visible
    this.getBuildingList()
  },
  methods: {
    handleChange(value) {
      console.log('选择', value)
    },
    getData() {
      console.log('获取数据')
      getUserBuildings(this.data.id).then(res => {
        this.checkedBuilding = res.data.map(v => {
          return v.id
        })
      })
    },
    handleClose() {
      console.log('点击关闭')
      this.beforeClose()
    },
    handleSubmit() {
      console.log('点击确定', this.data, this.checkedBuilding)
      setUserBuildings({ id: this.data.id, buildingIds: this.checkedBuilding }).then(res => {
        console.log('res', res)
        this.$notify.success('保存成功')
        this.handleClose()
      })
    },
    beforeClose() {
      console.log('关闭前的回调')
      this.show = false
      this.$emit('update:visible', false)
    },
    close() {
      console.log('关闭的回调')
    },
    closed() {
      console.log('关闭动画结束后的回调')
      this.checkedBuilding = []
    }
  }
}
</script>

<style scoped>

</style>
